﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Threading;
using System.Configuration;

namespace FX.CC.Andon.UpgradePublisher
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        void ProcessData(object para)
        {
            var param = (ThreadParamWrapper)para;

            try
            {

                using (SqlConnection conn = new SqlConnection())
                {
                    conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCONN"].ConnectionString;
                    //Write Version
                    bool flag = false;
                    Guid vid = Guid.NewGuid();
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.CommandText =
    @"Delete From UT_CEVersion Where ClientType=@ct;
INSERT INTO UT_CEVersion (VersionID, ClientType, PubTime) VALUES (@vid,@ct,@ptime);";
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.Add(new SqlParameter("@vid", vid));
                        cmd.Parameters.Add(new SqlParameter("@ct", param.ClientType));
                        cmd.Parameters.Add(new SqlParameter("@ptime", DateTime.Now));
                        conn.Open();
                        flag = cmd.ExecuteNonQuery() > 0;
                    }

                    if (!flag)
                    {
                        //数据插入失败 停止执行
                        throw new Exception("写入数据失败");
                        //return;
                    }

                    using (DataTable dt = new DataTable("FSTab"))
                    {
                        dt.Columns.Add(new DataColumn("VersionID", typeof(Guid)));
                        dt.Columns.Add(new DataColumn("FileName", typeof(string)));
                        dt.Columns.Add(new DataColumn("BIN", typeof(byte[])));
                        foreach (var fileName in param.Files)
                        {
                            byte[] buffer;
                            using (FileStream fs = new FileStream(fileName, FileMode.Open))
                            {
                                long len = fs.Length;
                                buffer = new byte[len];
                                fs.Read(buffer, 0, buffer.Length);
                            }
                            string shortName = fileName.Split('\\').Last();
                            dt.Rows.Add(vid, shortName, buffer);
                        }

                        using (SqlBulkCopy blk = new SqlBulkCopy(conn))
                        {
                            blk.DestinationTableName = "UT_CEFile";
                            //blk.ColumnMappings.Add(new SqlBulkCopyColumnMapping())
                            blk.WriteToServer(dt);
                        }
                        dt.Rows.Clear();
                        dt.Columns.Clear();
                    }
                }
            }
            catch(Exception ex){
                this.Invoke(new Action<ProgressBar, string>((bar, err) =>
                {
                    bar.Visible = false;
                    _MsgBox.PopError(err);
                }), param.Bar, ex.Message);
                return;
            }

            this.Invoke(new Action<ProgressBar>((bar)=>{
                bar.Visible = false;
                _MsgBox.PopInfo("新版本发布成功！");
            }), param.Bar);
        }

        private void btnEqKanban_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + "\\设备看板程序\\";
            bool flag = Directory.Exists(path);
            if (!flag)
            {
                _MsgBox.PopWarning(string.Format("升级文件夹【{0}】不存在!", path));
                return;
            }

            string[] fileNames = Directory.GetFiles(path);
            if (fileNames.Length == 0)
            {
                _MsgBox.PopWarning("升级文件夹中无任何需发布的文件!");
                return;
            }

            var bar = pbEqKanban;
            var para = new ThreadParamWrapper { Files = fileNames, ClientType = 2, Bar = bar };
            Thread th = new Thread(new ParameterizedThreadStart(ProcessData));
            th.Start(para);
            bar.Visible = true;
        }

        private void btnController_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + "\\采集程序\\";
            bool flag = Directory.Exists(path);
            if (!flag)
            {
                _MsgBox.PopWarning(string.Format("升级文件夹【{0}】不存在!", path));
                return;
            }

            string[] fileNames = Directory.GetFiles(path);
            if (fileNames.Length == 0)
            {
                _MsgBox.PopWarning("升级文件夹中无任何需发布的文件!");
                return;
            }

            var bar = pbController;
            var para = new ThreadParamWrapper { Files = fileNames, ClientType = 0, Bar = bar };
            Thread th = new Thread(new ParameterizedThreadStart(ProcessData));
            th.Start(para);
            bar.Visible = true;
        }

        private void btnSumKanban_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + "\\综合看板程序\\";
            bool flag = Directory.Exists(path);
            if (!flag)
            {
                _MsgBox.PopWarning(string.Format("升级文件夹【{0}】不存在!", path));
                return;
            }

            string[] fileNames = Directory.GetFiles(path);
            if (fileNames.Length == 0)
            {
                _MsgBox.PopWarning("升级文件夹中无任何需发布的文件!");
                return;
            }

            var bar = pbSumKanban;
            var para = new ThreadParamWrapper { Files = fileNames, ClientType = 1, Bar = bar };
            Thread th = new Thread(new ParameterizedThreadStart(ProcessData));
            th.Start(para);
            bar.Visible = true;
        }
    }

    public class ThreadParamWrapper {
        public string[] Files { get; set; }
        public int ClientType { get; set; }
        public ProgressBar Bar { get; set; } 
    }

    public static class _MsgBox
    {
        public static DialogResult PopInfo(string content)
        {
            return MessageBox.Show(content, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
        }

        public static DialogResult PopWarning(string content)
        {
            return MessageBox.Show(content, "警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
        }

        public static DialogResult PopError(string content)
        {
            return MessageBox.Show(content, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
        }

        public static DialogResult PopQuestion(string content)
        {
            return MessageBox.Show(content, "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
        }
    }
}
